<template>
  <div style="margin: 1vh 1vw">
    <el-select v-model="campus" placeholder="请选择校区" @change="fetch" v-if="role===1"
               style="margin-bottom: 20px; width: 10vw">
      <el-option
          v-for="item in campusList"
          :key="item.id"
          :label="item.campusName"
          :value="item.id"
          style="text-align: center"
      />
    </el-select>
  </div>

  <div id="data-dashboard">
    <el-card :style="role===0?'width: 35%;height: 600px;':'width: 25%;height: 400px;'">
      <template #header>
        <div class="card-header">
          <span>公告栏</span>
        </div>
      </template>
      <div class="announcement-board">
        <ul>
          <li v-for="item in announcements.data">
            <el-button text type="primary" @click="openAnnouncementDialog(item)">
              {{ item.title }}
            </el-button>
          </li>
        </ul>
      </div>
    </el-card>
    <el-card style="width: 25%;height: 400px;" v-if="role!==0">
      <template #header>
        <div class="card-header">
          <span>今日工作</span>
        </div>
      </template>
      <div class="work-today">
        <div class="work-today-tittle">
          今日会议:
        </div>
        <div class="work-today-board">
          <data-containers v-for="item in workToday" :title="item.title" :unit="item.unit" :value="item.value"/>
        </div>
        <div class="work-today-tittle">
          审核情况:
        </div>
        <div class="work-today-board">
          <data-containers v-for="item in approvalStatistics" :title="item.title" :unit="item.unit"
                           :value="item.value"/>
        </div>
      </div>
    </el-card>
    <el-card style="width: 40%;height: 400px" v-if="role!==0">
      <template #header>
        <div class="card-header">
          <span>会议室使用率</span>
        </div>
      </template>
      <div id="usage-chart" style="width: 100%; height:300px"></div>
    </el-card>
    <el-card style="width: 35%;height: 600px;" v-if="role!==0">
      <template #header>
        <div class="card-header">
          <span>今日会议</span>
        </div>
      </template>
      <div>
        <el-table :data="conferenceInToday" style="width: 100%">
          <el-table-column prop="topic" label="会议主题"/>
          <el-table-column prop="roomName" label="会议室"/>
          <el-table-column label="时间">
            <template #default="scope">
              {{ scope.row.startTime.substring(0, 5) }} - {{ scope.row.endTime.substring(0, 5) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-card style="width: 60%;height: 600px;" body-style="padding: 0">
      <el-calendar
          header-style="padding:20px"
          class="conference-calendar"
          ref="calendar"
          v-model="calendarDate"
      >
        <template #header="{ date }">
          <span>我的会议</span>
          {{ date }}
          <el-button-group>
            <el-button size="small" @click="selectDate('prev-year')">《</el-button>
            <el-button size="small" @click="selectDate('prev-month')">＜</el-button>
            <el-button size="small" @click="selectDate('today')">今天</el-button>
            <el-button size="small" @click="selectDate('next-month')">＞</el-button>
            <el-button size="small" @click="selectDate('next-year')">》</el-button>
          </el-button-group>
        </template>
        <template #date-cell="{data}">
          {{ Number(data.day.split('-')[2]) }}<span style="font-size: 10px;margin-left: 5px">{{
            getConferences(data.day).length > 0 ? '(' + getConferences(data.day).length + ')'
                : ''
          }}</span>
          <div class="conference-list">
            <ul v-if="hasConference(data.day)">
              <li v-for="conference in getConferences(data.day)"
                  :key="conference.id">
                <el-button
                    text
                    class="to-conference"
                    @click="handleConference(conference.id)"
                >
                  {{ conference.topic }}
                </el-button>
              </li>
            </ul>
          </div>
        </template>
      </el-calendar>
    </el-card>
    <el-dialog class="announcement-dialog" v-model="announcementDialog.visible" destroy-on-close @close="fetch">
      <AnnouncementDetails :status="announcementDialog.status"
                           :id="announcementDialog.id"
                           v-model:visible="announcementDialog.visible"></AnnouncementDetails>
    </el-dialog>
  </div>
</template>

<script>

import * as echarts from 'echarts';
import {
  GetConferenceByMonth,
  GetConferenceInToday,
  GetConferenceStatistics,
  GetUsageRate,
  PageAnnouncements
} from "@/api/index.js";
import DataContainers from "@/components/DataContainers.vue";
import AnnouncementDetails from "@/components/AnnouncementDetails.vue";
import {debounce} from "lodash";

export default {
  name: 'DataDashboard',
  components: {AnnouncementDetails, DataContainers},
  created() {
    this.fetch();
  },
  props: {},
  data() {
    return {
      announcementDialog: {
        visible: false,
        id: '',
        status: '',
        title: '',
      },
      announcements: {
        queryForm: {
          total: 0,
          pageNum: 1,
          pageSize: 10,
        },
        data: [],
      },
      calendarDate: new Date(),
      campus: JSON.parse(localStorage.getItem('WFITInfo')).campus,
      conferenceInMonth: [],
      conferenceInToday: [],
      workToday: [
        {
          title: '会议中',
          value: 0,
          unit: '次'
        },
        {
          title: '待开始',
          value: 0,
          unit: '次'
        },
        {
          title: '已结束',
          value: 0,
          unit: '次'
        },

      ],
      approvalStatistics: [
        {
          title: '待审核',
          value: 0,
          unit: '次'
        },
        {
          title: '已过期',
          value: 0,
          unit: '次'
        },
      ]
    }
  },
  methods: {
    selectDate(type) {
      if (!this.$refs.calendar) return
      this.$refs.calendar.selectDate(type)
      // 保持原有的月份数据获取逻辑
      this.fetchCalendarConference(this.calendarDate.getMonth() + 1)
    },
    openAnnouncementDialog(item) {
      this.announcementDialog = {
        visible: true,
        id: item.id,
        status: 'preview',
      }
    },
    fetch() {
      if (this.role === 1) {
        this.fetchUsageRateData();
        this.fetchConferenceStatistics()
        this.fetchConferenceInToday()
      }
      this.fetchAnnouncements()
      this.fetchCalendarConference(this.calendarDate.getMonth() + 1 || new Date().getMonth() + 1)
    },
    fetchAnnouncements() {
      PageAnnouncements(this.announcements.queryForm).then(res => {
        this.announcements.data = res.data.rows;
        this.announcements.queryForm.total = +res.data.total
      })
    },
    fetchConferenceInToday() {
      GetConferenceInToday(this.campus).then((res) => {
        if (res.code === 200) {
          this.conferenceInToday = res.data;
        }
      })
    },
    fetchCalendarConference:debounce(function (month) {
      GetConferenceByMonth(this.campus, month).then((res) => {
        if (res.code === 200) {
          this.conferenceInMonth = res.data;
        }
      })
    },500),
    fetchConferenceStatistics() {
      GetConferenceStatistics(this.campus).then((res) => {
        if (res.code === 200) {
          this.workToday = [
            {title: '会议中', value: res.data.ongoingmeetings, unit: '次'},
            {
              title: '待开始', value: res.data.upcomingmeetings, unit: '次'
            },
            {

              title: '已结束', value: res.data.endedmeetings, unit: '次'
            },]
          this.approvalStatistics = [
            {

              title: '待审核',
              value: res.data.pendingmeetings,
              unit: '次'
            },
            {

              title: '已过期',
              value: res.data.expiredmeetings,
              unit: '次'
            },
          ]
        }
      });
    },
    fetchUsageRateData() {
      GetUsageRate(this.campus).then((res) => {
        if (res.code === 200) {
          this.initUsageRateChart(res.data);
        }
      });
    },
    initUsageRateChart(data) {
      const usageChart = echarts.init(document.getElementById('usage-chart'));
      // 处理数据，转换为饼图所需格式
      const pieData = data.map(item => ({
        value: item.totalHours, // 假设totalHours是使用时长
        name: item.roomName
      }));
      usageChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}小时 ({d}%)' // 提示信息格式
        },
        legend: {
          orient: 'horizontal',
          left: 'left',
          top: 'bottom'
        },
        series: [
          {
            name: '使用率',
            type: 'pie',
            radius: '50%',
            data: pieData, // 使用处理后的数据
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      });
    },
    hasConference(date) {
      return this.conferenceInMonth.some(conference => conference.date === date);
    },
    getConferences(date) {
      return this.conferenceInMonth.filter(conference => conference.date === date);
    },
    handleConference(id) {
      this.$router.push({
        name: 'ConferenceReservations',
        query: {
          status: 'check',
          conferenceId: id,
        },
      });
    },
  },
  computed: {
    campusList() {
      return this.$store.getters.getCampusList
    },
    role() {
      return this.$store.getters.getRole
    },
  },
  watch: {
    calendarDate(newValue, oldValue) {
      if (newValue.getMonth() !== oldValue.getMonth()) {
        this.fetchCalendarConference(newValue.getMonth() + 1)
      }
    }
  },
}
</script>

<style lang="less" src="@/assets/style/DashBoard.less"></style>